/**
 * Created by Brook on 2020/4/9.
 */

(function () {
    var async = require('async');
    var http = require('http')
    var moment = require('moment')
    var uuid = require('node-uuid');
    var sql_config = require('../../serverconfig.js');
    var model_sql = require('../../tool/db_helper.js').init(sql_config.Model_Config);
    var SQL_TXT = sql_config.SQL_TXT;
    var https = require('https');
    var valid = require('url-valid');
    var urlencode = require('urlencode');




    //回传参数
    var data = {
        "message": "请求成功",
        "data": {
            "status": 200,
            "model_id": null,
            "project_id": null,
            "status_text": "",
            "error_message": null,
            "error_stacks": null
        }
    };


    //接收请求 - 写入相关数据
    exports.post_parse = function(req, res) {
        async.auto({
            check_pars:function(cb){
                res.header('Access-Control-Allow-Origin', '*');
                console.log("=====>>>", req.body)
                cb(null, req.body)
            },
            //判断请求地址
            check_request_ip:['check_pars', function (cb, result) {
                var ip = getClientIP(req);

                //if (!/::1|106.52.70.77|193.112.44.252|218.23.36.18/.test(ip)) {
                //     data.data.status = 201;
                //     data.data.status_text = '仅接受指定服务器的文件';
                //     res.json(data);
                // } else {
                cb(null, [])
                // }
            }],
            //判断请求参数
            check_request_parameter:['check_request_ip', function (cb, result) {
                var {filePath, fileId, projectId, notifyUrl, md5} = result.check_pars;
                if (!filePath || !fileId) {
                    data.data.status = 202;
                    data.data.status_text = '参数不正确';
                    res.json(data);
                } else {
                    cb(null, []);
                };
            }],
            //判断下载地址参数
            check_path:['check_request_parameter', function (cb, result) {
                var info = result.check_pars;
                var filepaths = urlencode.decode(info.filePath);
                var str =encodeURI(filepaths);

                //判断模型地址
                valid(str, function (err, valid) {if (err) throw err;
                    if (!valid) {
                        data.data.status = 204;
                        data.data.status_text = '模型下载地址参数异常';
                        res.json(data);
                    } else {
                        cb();
                    };
                });
            }],
            //判断模型格式
            get_suffix:['check_path', async function (cb, result) {
                var info = result.check_pars;

                var ha = new httpAsync();
                var res_path = await ha.GetAsync(info.filePath);
                if (!res_path.headers['content-disposition']) {
                    console.log('Warning Res.Headers')
                    var filepath = urlencode.decode(info.filePath);
                    var suffix = filepath.split('.')[filepath.split('.').length - 1];
                    var modelname = filepath.split('/')[filepath.split('/').length - 1];
                } else {
                    var filename = res_path.headers['content-disposition'].match(/(filename=(.*))/)[2];
                    var suffix = filename.split('.')[filename.split('.').length - 1];
                    var modelname = filename;
                };
                console.log("model suffix ：", suffix);
                info["suffix"] = suffix;
                info["filename"] = modelname;
                cb(null, info)
            }],
            check_model_format:['get_suffix', function (cb, result) {
                if (!/skp|rvt|3dm|pla|rfa/.test(result.get_suffix.suffix)) {
                    data.data.status = 203;
                    data.data.status_text = '模型格式异常';
                    res.json(data);
                } else {
                    if (/skp/.test(result.get_suffix.suffix)) {
                        //result.get_suffix.gltfstate = '1';
                        result.get_suffix.gltfstate = '0';
                    } else {
                        result.get_suffix.gltfstate = '0';
                    }
                    cb(null, result.get_suffix);
                };
            }],
            //正确响应
            response_data:['check_model_format', function (cb, result) {
                data.data.status = 200;
                data.data.status_text = '模型格式转换中';
                console.log("Response request data success ...")
                res.json(data);
                cb(null, [])
            }],
            check_fileID:['response_data', function (cb, result) {
                model_sql.query(SQL_TXT.get_fileId,[result.get_suffix.fileId],function(db_err,db_result){
                    db_err?cb(db_err):cb(null,db_result);
                });
            }],
            up_db:['check_fileID', function(cb, result) {
                if (result.check_fileID.length != 0) {
                    cb(null, []);
                    /*
                    if (/3|4/.test(result.check_fileID[0].parsingstate)) {
                        cb(null, []);
                        model_sql.query(SQL_TXT.up_model_info,[result.get_suffix.fileId],function(db_err,db_result){
                            console.log("delete sql success ... ")
                            db_err?cb(db_err):cb(null,db_result);
                        });
                    };
                     */
                } else {
                    let model_data = [];
                    model_data = [
                        uuid.v1(),
                        result.get_suffix.fileId,
                        urlencode.decode(result.get_suffix.filePath),
                        result.get_suffix.projectId,
                        result.get_suffix.notifyUrl,
                        result.get_suffix.suffix,
                        result.get_suffix.filename,
                        urlencode.decode(result.get_suffix.modelName),
                        urlencode.decode(result.get_suffix.projectName),
                        result.check_model_format.gltfstate,
                        moment().format('YYYYMMDD'),
                        moment().format('YYYY-MM-DD HH:mm:ss')
                    ];

                    model_sql.query(SQL_TXT.insert_model_info,model_data,function(db_err,db_result){
                        console.log("insert sql success ... ")
                        db_err?cb(db_err):cb(null,db_result);
                    });
                };
            }]
        },function(err,results){
            if(err){
                console.log(err);
                res.json();
            }else{
                //console.log(r);
            };
        });
    };


    //HTTP请求获取Headers
    class httpAsync {
        varructor() {
        }
        async GetAsync(url) {

            var filepaths = urlencode.decode(url);
            var type = filepaths.split("://");
            var str =encodeURI(filepaths);

            var promise = new Promise(resolve => {
                if (type[0] == 'http') {
                    http.get(str, res => {
                        //console.log(res)
                        resolve(res);
                    });
                } else {
                    https.get(str, res => {
                        //console.log(res)
                        resolve(res);
                    });
                };
            });
            return promise;
        }
    }

    /**
     * @getClientIP
     * @desc 获取用户 ip 地址
     * @param {Object} req - 请求
     */
    function getClientIP(req) {
        return req.headers['x-forwarded-for'] || // 判断是否有反向代理 IP
            req.connection.remoteAddress || // 判断 connection 的远程 IP
            req.socket.remoteAddress || // 判断后端的 socket 的 IP
            req.connection.socket.remoteAddress;
    };

}).call(this);
